import React, { useEffect, useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import Contacts from "@/components/Contacts";
import Welcome from "@/components/Welcome";
import Cookies from "js-cookie";
import { logOut, getContacts } from "@/apis/common";
import ChatContainer from "@/components/ChatContainer";
import useSocket from "@/Hooks/useSocket";
import { flushSync } from "react-dom";

export default function Chat() {
  const navigate = useNavigate();
  const { socket, onSocketEvents, offSocketEvents } = useSocket(import.meta.env.VITE_API_URL, {
    auth: {
      token: Cookies.get("token"),
    }
  })

  const [contacts, setContacts] = useState([]); // 联系人列表
  const [currentChat, setCurrentChat] = useState(undefined); // 当前聊天对象
  const [currentUser, setCurrentUser] = useState(undefined); // 当前用户

  // 初始化时，如果设置了头像，则获取联系人列表，否则跳转到设置头像页面
  useEffect(() => {
    let user = localStorage.getItem(import.meta.env.VITE_USER_KEY)
    user = JSON.parse(user)
    if (user) {
      if (user.isAvatarImageSet) {
        // getContacts().then(([success, data]) => {
        //   if (success) {
        //     setContacts(data);
        //   }
        // });
      } else {
        navigate("/setAvatar");
      }
      setCurrentUser(user);
    } else {
      navigate("/login");
    }
  }, []);


  useEffect(() => {
    const events = {
      "users": (onlineUsers, contacts) => {
        const newContacts = [];
        contacts.forEach(contact => {
          if (onlineUsers[contact._id]) {
            contact.online = true;
            newContacts.unshift(contact);
          } else {
            contact.online = false;
            newContacts.push(contact);
          }
          return contact;
        })
        setContacts(newContacts);
      },
      "online": (userId) => {
        const newContacts = contacts.map(contact => {
          if (contact._id === userId) {
            contact.online = true;
          }
          return contact;
        })
        setContacts(newContacts);
        console.log(userId, "用户上线", newContacts)
      },
      "offline": (userId) => {
        const newContacts = contacts.map(contact => {
          if (contact._id === userId) {
            contact.online = false;
          }
          return contact;
        })
        setContacts(newContacts);
        console.log(userId, "用户下线", newContacts)
      },
      "conflict": (userId) => {
        console.log(userId, "账号在其他地方登录了，冲突下线")
        handleLogOut()
      },
      "connect_error": (err) => {
        console.log("连接失败，发生了错误", err)
      }
    }

    onSocketEvents(events)

    return () => {
      offSocketEvents(events)
    }
  }, [contacts])

  // 切换聊天对象
  const handleChatChange = (user) => {
    setCurrentChat(user);
  }

  // 退出登录
  const handleLogOut = async() => {
    const [success] = await logOut();
    if (success) {
      Cookies.remove("token");
      localStorage.removeItem(import.meta.env.VITE_USER_KEY)
      navigate("/login");
    }
  }

  return (
    <>
      <Container>
        <button onClick={handleLogOut}>退出登录</button>
        <div className="container">
          {/* 左侧联系人列表 */}
          <Contacts contacts={contacts} changeChat={handleChatChange} />

          {/* 右侧内容列表 */}
          {currentChat === undefined ? (
            <Welcome />
          ) : (
            <ChatContainer currentChat={currentChat} currentUser={currentUser} socket={socket} />
          )}
        </div>
      </Container>
    </>
  );
}

const Container = styled.div`
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 1rem;
  align-items: center;
  background-color: #131324;
  .container {
    height: 85vh;
    width: 85vw;
    background-color: #00000076;
    display: grid;
    grid-template-columns: 25% 75%;
    @media screen and (min-width: 720px) and (max-width: 1080px) {
      grid-template-columns: 35% 65%;
    }
  }
`;
